package com.jhecis.controller;

import com.jhecis.common.JsEngine;
import com.jhecis.dto.ApiData;
import com.jhecis.dto.ExecParm;
import com.jhecis.dto.ScriptContent;
import com.jhecis.service.InterfaceToolService;
import com.jhecis.dto.CommonResult;
import com.jhecis.po.InterfaceToolEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RequestMapping("/InterfaceTool")
@RestController
public class InterfaceToolController {

    @Resource
    private InterfaceToolService repository;

//    @Resource
//    YfcHelper yfcHelper;

    @GetMapping("/Test")
    public ApiData test() {
        //引入外部jar包调用方法
        ApiData res = new ApiData();
       // res.setData(yfcHelper.getData());
        return res;
    }

    @GetMapping("/GetInterfaceTool")
    public ApiData getInterfaceTool() {
        ApiData res = new ApiData();
        res.setData(repository.getInterfaceTool());
        return res;
    }

    @GetMapping("/GetInterfaceToolByCode")
    public ApiData getInterfaceToolByCode(String interfaceCode) {
        ApiData res = new ApiData();
        res.setData(repository.getInterfaceToolByCode(interfaceCode));
        return res;
    }

    @PostMapping("/SaveInterfaceTool")
    public ApiData saveInterfaceTool(@RequestBody List<InterfaceToolEntity> interfaceToolList) {
        ApiData res = new ApiData();
        CommonResult com = repository.saveInterfaceTool(interfaceToolList);
        res.setData(com);
        return res;
    }

    @PostMapping("/SaveInterfaceToolNoClob")
    public ApiData saveInterfaceToolNoClob(@RequestBody List<InterfaceToolEntity> interfaceToolList) {
        ApiData res = new ApiData();
        CommonResult com = repository.saveInterfaceToolNoClob(interfaceToolList);
        res.setData(com);
        return res;
    }

    @Autowired
    private JsEngine jsEngine;

    @PostMapping("/execInterfaceByParm")
    public ApiData execInterfaceByParm(@RequestBody ExecParm execParm) {
        ApiData res = new ApiData();
        //先通过code 获取 js代码。
        InterfaceToolEntity interfaceToolEntity = repository.getInterfaceToolByCode(execParm.interfacecode);
        String returnData = "";
        if (interfaceToolEntity != null) {
            //2.拼装执行调用js引擎，所需参数 1.脚本，2.入参 2.脚本中的入口函数名
            ScriptContent script = new ScriptContent();
            script.Data = execParm.data;
            script.FunctionName = interfaceToolEntity.getFunctionname();
            script.JavaScriptCode = interfaceToolEntity.getJavascriptcode();
            //2.执行js脚本
            try {
                returnData = jsEngine.execJs(script);
                res.setData(returnData);
            } catch (Exception e) {
                //记录日志吧
            }

        }
        return res;
    }
}
